import { useGlobalStore } from "~~/store/global";
import { useUserStore } from "~~/store/modules/user";
import { useEventBus } from "@vueuse/core";
import { compare } from "~/utils/calculation";
// import { navigateI18nTo } from "@/utils";
import { getUserInfo } from "../api/user";
import { JUMPAPPS } from "~/config";

// 用于存储各个函数的私有变量
const fnVar: any = {};

/**
 * @description: 安卓版本兼容校验
 * @param {*} isAndroid
 * @param {any} param 一个 packageVersion 版本数组
 * @return {*} true 通过,false 不通过
 * @author: Berry
 */
const AndroidVerify = (isAndroid = false, param: any = []) => {
  // 1. 安卓 兼容(新包,老包)处理(iOS 不需要兼容,新包会把所有的都带上)
  if (isAndroid) {
    if (param.length > 0) {
      const globalStore = useGlobalStore();
      let comparison = "";
      // 匹配对应前缀的版本
      comparison = param.find((element: string) => {
        if (element) {
          const packagePrefix = element.split("-")[0];
          return globalStore.packagePrefix === packagePrefix;
        }
      });
      if (!comparison) return false;
      // 1.1 开始比对
      const compareVersion = compare(globalStore.packageId, comparison);
      console.log("--compareVersion--", compareVersion);

      // 版本比较: 0 版本相同
      if (compareVersion === undefined || compareVersion < 0) {
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  }
};

class Bridge {
  /**
   * @description: 默认浏览器打开链接
   */
  defaultBrowserOpen(url: string) {
    if (!url) return false;
    try {
      if (window?.JSCallAndroid) {
        if (
          bridgeVersionCheck(JUMPAPPS().defaultBrowserOpen()) &&
          window?.JSCallAndroid?.externalWeb
        ) {
          return window?.JSCallAndroid?.externalWeb(url);
        } else {
          window.location.href = url;
          // 自己加载h5 需要额外处理返回功能
          // navigateI18nTo({
          //   path: "/webview",
          //   query: {
          //     src: url,
          //   },
          // });
          return;
        }
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        return window.webkit.messageHandlers.GoPageEvent.postMessage({
          page: "newWeb",
          link: url,
        });
      }
    } catch (error) {
      console.log(error);
      return false;
    }
  }

  /**
   * @description: 1. vue 暴漏给 APP 的桥接方法
   * @author: Berry
   */
  exportFn() {
    if (!window) return;

    /**
     * @description: BD Dana 用户点击虚拟返回按键： return true 拦截, false 不拦截; 随时可控
     * 1. 先判断是否拦截。
     * 2. 拦截的场景下，通知导航的返回事件
     * @return {*}
     * @author: Berry
     */
    const interceptAppBack = () => {
      const globalStore = useGlobalStore();
      if (globalStore.$state.isInterceptAppBack) {
        const onInterceptAppBack = useEventBus(
          "bridge-onInterceptAppBack-emit"
        );
        onInterceptAppBack.emit();
        return true;
      } else {
        return false;
      }
    };
    // 安卓端
    if (window?.JSCallAndroid) {
      // BD Dana 用户点击虚拟返回按键： return true 拦截, false 不拦截; 随时可控
      window.onBackPressed = function () {
        console.log("BD 安卓 APP 返回上一级");
        return interceptAppBack();
      };
      // FD 用户点击虚拟返回按键： return true 拦截, false 不拦截; 随时可控
      window.onBack = function () {
        console.log("FD 安卓 APP 返回上一级");
        return interceptAppBack();
      };
    }
    // iOS 端
    else {
      // 1. 获取剪贴板,内容,函数
      window.getPasteToH5 = function (val: string) {
        const getPasteToH5Emit = useEventBus("bridge-getPasteToH5-emit");
        console.log("收到iOS通知getPasteToH5,参数是:", val);
        if (val) getPasteToH5Emit.emit(val);
      };
      // 2.实现在二级等深层页面的场景下，侧滑返回的时候，返回上一级，而不是返回 App
      if (window?.webkit?.messageHandlers?.pageEvent?.postMessage) {
        window.webkit.messageHandlers.pageEvent.postMessage("needPopBack");
      }
      /**
       * @description: 3. 拦截iOS侧滑，用户侧滑以后，的回调事件；搭配使用 xxxxxx.pageEvent.postMessage({"goBackState": "0"}) // 0: 不需要app返回  1. 需要app的返回
       * 1. 进入页面就要调用 goBackState 来通知 iOS 是否需要拦截
       * 2. 从这个页面离开，还需要调用 goBackState 来通知 iOS 不需要拦截了；
       */
      window.onSideslipBackiOS = function () {
        console.log("iOS APP 返回上一级");
        interceptAppBack();
      };
    }
  }

  /**
   * @description: 搭配 onSideslipBackiOS 一起实现，拦截侧滑返回的功能
   * @author: Berry
   */
  goBackStateiOS(val: number) {
    try {
      if (window?.webkit?.messageHandlers?.pageEvent?.postMessage) {
        window.webkit.messageHandlers.pageEvent.postMessage({
          goBackState: val || 0, //  0: 不需要app返回  1. 需要app的返回
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * @description: 获取剪贴板内容
   * @param {any} call 回调函数
   * @return {*} 无需返回值
   * @author: Berry
   */
  getAppCopyValue(call: any, isAndroid = false, param: any = {}) {
    try {
      if (window?.JSCallAndroid) {
        if (AndroidVerify(isAndroid, param)) {
          call((window as any).JSCallAndroid["getClipboard"]());
        } else {
          call(false);
        }
      } else if (window?.webkit?.messageHandlers?.pageEvent?.postMessage) {
        // 1. 创建回调通知
        const getPasteToH5Emit = useEventBus("bridge-getPasteToH5-emit");
        getPasteToH5Emit.on(call);
        // 2. 告诉 iOS 根据pageEvent标识,paste,则需要获取剪贴板内容
        window.webkit.messageHandlers.pageEvent.postMessage("paste");
      }
    } catch (error) {
      console.log("getAppCopyValue:", error);
      call(false);
    }
  }

  /**
   * @description: 保存图片到相册
   */
  saveImageToAlbum() {
    try {
      if (window?.JSCallAndroid) {
        // return (window as any).JSCallAndroid["saveImageToGallery"]();
        return '这里无需桥接,直接长按识别,图片链接中的唯一标识参数例如: https://test-bdc.btcdana.org/fx/image/qrcode/xyx65.png?btcdanaAppH5Bridge=0426"  唯一标识:btcdanaAppH5Bridge=0426';
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        // return window.webkit.messageHandlers.GoPageEvent.postMessage({
        //   router: url,
        // });
      }
    } catch (error) {
      console.log(error);
      return false;
    }
  }

  /**
   * @description: 使用原生函数跳转,原生页面(iOS没有这种方式,安卓独有) 2024.04.09 snow
   */
  jumpAppFnRoute(url: string, param?: any) {
    if (!url) return;
    try {
      if (window?.JSCallAndroid) {
        if (param) {
          return (window as any).JSCallAndroid[url](param); // onBackActivity('mine') 方法名 onBackActivity 参数 mine
        }
        if (url.startsWith("https://")) {
          return window?.JSCallAndroid?.jump(url);
        } else {
          return (window as any).JSCallAndroid[url]();
        }
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        // return window.webkit.messageHandlers.GoPageEvent.postMessage({
        //   router: url,
        // });
      }
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * @description:
   * 1.
   * @return {*} 返回值
   */

  /**
   * @description: 跳转原生页面
   * @param {string} url 唯一标识
   * @param {*} isAndroid 是否执行安卓兼容逻辑
   * @param {any} param 安卓/iOS  通用参数
   * @author: Berry
   */
  jumpAppRoute(url: string, isAndroid = false, param: any = {}) {
    if (!url) return;
    // 1. 安卓 兼容(新包,老包),跳转处理
    if (isAndroid) {
      if (param.compatibleVersionList) {
        const globalStore = useGlobalStore();
        let comparison: any = "";
        // 匹配 packageId
        comparison = param.compatibleVersionList.find((e: string) => {
          return e.split("-")[0] === globalStore.packagePrefix;
        });

        if (!comparison) {
          // 无需比对,直接跳转到兼容页面
          this.jumpAppRoute(param.jumpUrl);
          return;
        }

        // 1.1 开始比对
        const compareVersion = compare(globalStore.packageId, comparison);
        console.log("兼容比对:", compareVersion);

        // 版本比较: 0 版本相同
        if (compareVersion === undefined || compareVersion < 0) {
          const uTemp = param.jumpUrl || JUMPAPPS()["mine"];
          console.log("❌不兼容:", uTemp);
          this.jumpAppRoute(uTemp);
          return;
        } else {
          console.log("✅兼容:", url);
          return this.jumpAppFnRoute(url);
        }
      } else {
        return this.jumpAppFnRoute(url);
      }
    }
    // 2. iOS 目前只有一个 app 无需处理
    // 3. 通用跳转
    try {
      if (window?.JSCallAndroid?.jump) {
        return window?.JSCallAndroid?.jump(url);
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        return window.webkit.messageHandlers.GoPageEvent.postMessage({
          router: url,
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 设置标题
   *
   * @param title 标题
   */
  setTitle(title: string) {
    try {
      if (window?.JSCallAndroid?.setTitle) {
        window?.JSCallAndroid?.setTitle(title);
      } else if (window?.webkit?.messageHandlers?.pageEvent?.postMessage) {
        window.webkit.messageHandlers.pageEvent.postMessage({
          setTitle: title,
        });
      }
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * 隐藏原生头部导航栏
   */
  hideToolbar() {
    try {
      if (window?.JSCallAndroid?.hideToolbar) {
        return window?.JSCallAndroid?.hideToolbar();
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        //window?.webkit?.messageHandlers?.GoPageEvent?.postMessage(title)
        window?.webkit?.messageHandlers?.pageEvent.postMessage({
          hiddenNavigationBar: "1",
        });
      }
    } catch (error) {
      console.log(error);
      return 0;
    }
  }
  /**
   *
   * @param go 0: 返回上一级页面 1: 返回到首页
   */
  onAppBack(go: "0" | "1") {
    try {
      if (window?.JSCallAndroid?.onBack) {
        window?.JSCallAndroid?.onBack();
      } else if (
        window?.webkit?.messageHandlers?.nativePopMethod?.postMessage
      ) {
        window?.webkit?.messageHandlers?.nativePopMethod?.postMessage(go);
      }
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 跳转App登录页面
   */
  onAppLogin() {
    if (!process.client || fnVar.onAppLogin) return;
    const globalStore = useGlobalStore();
    if (!globalStore.$state.isCallAppDone) return;
    fnVar.onAppLogin = true;
    // 这里设置延迟,是为了兼容,某些ios 手机,因为在 setup 中没有获取到 token,就立马跳转登录的场景
    setTimeout(() => {
      fnVar.onAppLogin = false;

      // 1. 在检查一下是不是真的没有
      if (globalStore.$state.token) return;
      console.error("未获取到 token / token失效 => 跳转登录页");
      //  globalStore.$state.isDhApp
      if (
        window?.JSCallAndroid?.onLogin ||
        window?.webkit?.messageHandlers?.GoPageEvent?.postMessage
      ) {
        // 1.1 isRetry 如果桥接没有获取到 Token,单页面切换,或者,再次进入h5页面后会重试，获取 token
        globalStore.$patch({
          isRetry: true,
        });
        // 2. 离开 h5 之后,不需要上传其他错误
        const closeUploadEmit = useEventBus("qdjkWeb-closeUpload-emit");
        closeUploadEmit.emit(false);

        // 3. 跳转
        try {
          if (window?.JSCallAndroid?.onLogin) {
            window?.JSCallAndroid?.onLogin();
          } else if (
            window?.webkit?.messageHandlers?.GoPageEvent?.postMessage
          ) {
            const iOSLoginFn = () => {
              localStorage.removeItem("token");
              localStorage.removeItem("iosToken");

              let compareVersionLogin: any = compare(
                globalStore.$state.packageId,
                "BtcDana.IOS-1.3.7-com.indone.online-ios"
              );
              if (compareVersionLogin >= 0) {
                window?.webkit?.messageHandlers?.GoPageEvent?.postMessage({
                  // router: "https://btcdana.com/LoginActivity",  // 会
                  router: "https://btcdana.com/LoginActivity?isReplace=1", // 不会返回到跳转前的页面
                });
              } else {
                window?.webkit?.messageHandlers?.GoPageEvent?.postMessage({
                  // router: "native://page/login",  // 会
                  router: "native://page/login?isReplace=1", // 不会返回到跳转前的页面
                });
              }
            };
            // 3.1 获取缓存(这里没有调用getAppToken是因为,猜测应该03.callApp.client已经调用了且没有返回)
            const token_local =
              localStorage.getItem("token") || localStorage.getItem("iosToken");
            if (token_local) {
              // 3.2 重新赋值,app 传递给 h5 的useRequestHeaders信息
              const language_local = localStorage.getItem("language");
              const packageId_local = localStorage.getItem("packageId");
              const statusBarHeight_local =
                localStorage.getItem("statusBarHeight");
              const IsIphoneX_local = localStorage.getItem("IsIphoneX");
              globalStore.$patch((state) => {
                state.token = token_local;
                state.language = language_local || "en";
                state.packageId = packageId_local || "";
                state.statusBarHeight = Number(statusBarHeight_local) || 0;
                state.IsIphoneX = Number(IsIphoneX_local) == 1 ? true : false;
              });

              //  3.3 获取用户信息
              getUserInfo().then((res) => {
                // console.log("--用户信息--", res);
                if (res && res.code === 200 && res.data?.user) {
                  const userState = useUserStore();
                  userState.$state = res.data.user as any;
                  // 没有生效
                  // navigateI18nTo({
                  //   path: "/mvp/coin/coin",
                  // });
                } else {
                  iOSLoginFn();
                }
              });
            } else {
              iOSLoginFn();
            }
          }
        } catch (error) {
          console.log(error);
        }
      }
    }, 1800);
  }

  /**
   * 获取用户token
   */
  getAppToken(): string {
    // if(process.env.NODE_ENV == "development") return ''
    try {
      // 安卓token
      if (window?.JSCallAndroid?.getToken) {
        const token = window?.JSCallAndroid?.getToken();
        sessionStorage.setItem("token", token);
        const tokens = sessionStorage.getItem("token");
        return tokens ?? "";
      }
      // ios token
      else {
        const token = sessionStorage.getItem("token");
        const local_token = localStorage.getItem("iosToken");
        return token || local_token || "";
      }
    } catch (error) {
      console.log(error);
    }

    return "";
  }

  /**
   * 获取当前语言
   */
  getAppLanguage(): string {
    try {
      const language = window?.JSCallAndroid?.getLanguage();

      if (language) {
        sessionStorage.setItem("language", language);
        const languages = sessionStorage.getItem("language");
        // 安卓language
        return languages ?? "";
      } else {
        // ios language
        const language = sessionStorage.getItem("language");

        return language ?? "";
      }
    } catch (error) {
      console.log(error);
    }

    return "";
  }

  /**
   * 获取package-id
   **/
  getAppPackageId(): string {
    try {
      const packageId = window?.JSCallAndroid?.getPackageId();

      if (packageId) {
        sessionStorage.setItem("packageId", packageId);
        const packageIds = sessionStorage.getItem("packageId");
        // 安卓packageId
        return packageIds ?? "";
      } else {
        // ios packageId
        const packageId = sessionStorage.getItem("packageId");

        return packageId ?? "";
      }
    } catch (error) {
      console.log(error);
    }

    return "";
  }
  /**
   * 分享
   **/
  onShare(title: string, url: string) {
    try {
      if (window?.JSCallAndroid?.onShare) {
        window?.JSCallAndroid?.onShare(title, url);
      } else if (window?.webkit?.messageHandlers?.GoPageEvent?.postMessage) {
        const globalStore = useGlobalStore();
        let compareVersionShare: any = compare(
          globalStore.$state.packageId,
          "BtcDana.IOS-1.3.7-com.indone.online-ios"
        );
        if (compareVersionShare >= 0) {
          window?.webkit?.messageHandlers?.GoPageEvent?.postMessage({
            router: `https://btcdana.com/share?url=${url}&title=${title}`, // 不会返回到跳转前的页面
          });
        } else {
          window?.webkit?.messageHandlers?.GoPageEvent?.postMessage({
            router: "system://share?url=" + url + "&title=" + title,
          });
        }
      }
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 安卓独有: 功能有两个: 1. 打开外部链接 2.如果安卓安装了这个 app 可以直接打开
   * @param url
   */
  externalWeb(url: string) {
    try {
      // 暂时只有安卓有这个方法
      if (window?.JSCallAndroid?.externalWeb) {
        window?.JSCallAndroid?.externalWeb(url);
      }
    } catch (error) {
      console.log(error);
    }
  }
}

// let bridge = {};
// nextTick(() => {
//   bridge = new Bridge();
// });

// const bridge = process.client ? new Bridge() : new Object();

export const bridge = process.client ? new Bridge() : {};

export default process.client ? bridge : {};
